<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设备管理 - 智能设备控制中心</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .device-card {
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
            height: 100%;
        }
        .device-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .device-on {
            background-color: #e3f2fd;
            border-color: #90caf9;
        }
        .device-off {
            background-color: #f5f5f5;
        }
        .card-header {
            font-weight: bold;
        }
        .status-badge {
            font-size: 0.9rem;
        }
        .nav-link {
            color: #495057;
        }
        .nav-link.active {
            color: #0d6efd;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm mb-4">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="fa fa-home mr-2"></i>智能设备控制中心
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ml-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/devices">设备</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/scenes">场景</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/schedules">定时任务</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/analytics">数据分析</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="row">
            <div class="col">
                <h2 class="mb-4"><i class="fa fa-plug text-primary"></i> 设备管理</h2>
                <p class="mb-4">点击设备卡片可以切换设备状态，点击训练按钮可以训练AI使用模式模型。</p>
            </div>
        </div>

        <!-- 设备列表 -->
        <div class="row">
            {% for device in device_config %}
            <div class="col-md-3 mb-4">
                <div class="card device-card {{ 'device-on' if system_status.relays[device.id-1] else 'device-off' }}" onclick="toggleDevice({{ device.id }})">
                    <div class="card-header">
                        <i class="fa fa-{{ device.icon }}"></i> {{ device.name }}
                        <span class="float-right badge {{ 'bg-success' if system_status.relays[device.id-1] else 'bg-secondary' }}">
                            {{ '开启' if system_status.relays[device.id-1] else '关闭' }}
                        </span>
                    </div>
                    <div class="card-body">
                        <p class="card-text"><strong>位置：</strong>{{ device.room }}</p>
                        <p class="card-text"><strong>类型：</strong>{{ device.type }}</p>
                        {% if device.id <= 4 %}
                        <p class="card-text"><strong>电流：</strong>{{ system_status.currents[device.id-1] | round(2) }} A</p>
                        {% endif %}
                        <div class="mt-3">
                            <button class="btn btn-sm btn-info w-100" onclick="event.stopPropagation(); trainModel({{ device.id }})"><i class="fa fa-cogs"></i> 训练AI模型</button>
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>

        <!-- 房间分组 -->
        <div class="row mt-8">
            <div class="col">
                <h3 class="mb-3"><i class="fa fa-building text-primary"></i> 按房间查看</h3>
                <div class="list-group">
                    {% for room in rooms %}
                    <a href="/rooms/{{ room }}" class="list-group-item list-group-item-action">
                        <i class="fa fa-arrow-right mr-2"></i>{{ room }}
                        <span class="badge bg-primary float-right">{{ room_devices[room] | length }}</span>
                    </a>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 获取所有房间的设备数量
        const rooms = {};
        {% for device in device_config %}
        if (!rooms['{{ device.room }}']) {
            rooms['{{ device.room }}'] = 0;
        }
        rooms['{{ device.room }}']++;
        {% endfor %}
        
        // 切换设备状态
        function toggleDevice(deviceId) {
            // 获取当前状态并反转
            // 改用标准DOM API查询方法
            const cards = document.querySelectorAll('.card.device-card');
            let currentState;
            cards.forEach(card => {
                const header = card.querySelector('.card-header');
                if (header && header.textContent.includes(deviceId)) {
                    currentState = card.querySelector('.badge');
                }
            });
            
            if (!currentState) {
                console.error('未找到设备:', deviceId);
                return;
            }
            
            const state = currentState.classList.contains('bg-secondary');
            
            // 发送请求
            fetch('/api/toggle_relay', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    device_id: deviceId,
                    state: state
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 刷新页面
                    location.reload();
                } else {
                    alert('操作失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('操作失败');
            });
        }
        
        // 训练AI模型
        function trainModel(deviceId) {
            if (confirm('确定要为该设备训练AI使用模式模型吗？这将基于您的历史使用数据生成智能建议。')) {
                fetch('/api/train_usage_model', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ device_id: deviceId })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('模型训练成功！系统将基于您的使用习惯提供更智能的建议。');
                    } else {
                        alert('训练失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('训练失败');
                });
            }
        }
        
        // 定时更新系统状态
        function updateSystemStatus() {
            fetch('/api/get_status')
            .then(response => response.json())
            .then(data => {
                // 更新设备状态
                for (let i = 0; i < 8; i++) {
                    const deviceId = i + 1;
                    
                    // 改用标准DOM API查询方法
                    const cards = document.querySelectorAll('.card.device-card');
                    let badge;
                    cards.forEach(card => {
                        const header = card.querySelector('.card-header');
                        if (header && header.textContent.includes(deviceId)) {
                            badge = card.querySelector('.badge');
                        }
                    });
                    
                    if (badge) {
                        if (data.relays[i]) {
                            badge.className = 'float-right badge bg-success';
                            badge.textContent = '开启';
                            badge.closest('.device-card').className = 'card device-card device-on';
                        } else {
                            badge.className = 'float-right badge bg-secondary';
                            badge.textContent = '关闭';
                            badge.closest('.device-card').className = 'card device-card device-off';
                        }
                    }
                }
            })
            .catch(error => console.error('Error updating status:', error));
        }
        
        // 定时更新（每5秒）
        setInterval(updateSystemStatus, 5000);
        
        // 移除自定义的contains方法扩展
    </script>
</body>
</html>